package io.github.yotta.export.core.utils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class GenericTypeUtils {
    public static Class<?> getGenericType(Class<?> clazz, int index) {
        Type superclass = clazz.getGenericSuperclass();
        if (superclass instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) superclass;
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            if (index < actualTypeArguments.length) {
                Type actualTypeArgument = actualTypeArguments[index];
                if (actualTypeArgument instanceof Class) {
                    return (Class<?>) actualTypeArgument;
                }
            }
        }
        return null;
    }

    public static <T> Class<T> getGenericInterfaceType(Class<?> clazz, Class<?> interfaceClass, int index) {
        Type[] genericInterfaces = clazz.getGenericInterfaces();
        for (Type genericInterface : genericInterfaces) {
            if (genericInterface instanceof ParameterizedType) {
                ParameterizedType parameterizedType = (ParameterizedType) genericInterface;
                if (parameterizedType.getRawType() == interfaceClass) {
                    Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
                    if (index < actualTypeArguments.length) {
                        Type actualTypeArgument = actualTypeArguments[index];
                        if (actualTypeArgument instanceof Class) {
                            return (Class<T>) actualTypeArgument;
                        }
                    }
                }
            }
        }
        return null;
    }
}